// 战场名称和类型数据
const battleData = [
    { name: "周边遗迹群", type: "阵地战", short: "阵地", bgClass: "battle-0" },
    { name: "尘封秘岩", type: "争夺战", short: "尘封", bgClass: "battle-1" },
    { name: "荣誉野", type: "碎冰战", short: "碎冰", bgClass: "battle-2" },
    { name: "昂萨哈凯尔", type: "竞争战", short: "草原", bgClass: "battle-3" }
];

// 设定初始日期 (2025年7月17日为阵地战)
const initialDate = new Date(2025, 6, 17); // 注意：月份从0开始，7月是6
let currentDate = new Date();
let currentMonth = currentDate.getMonth();
let currentYear = currentDate.getFullYear();
let calendarMonth = currentMonth;
let calendarYear = currentYear;

// 获取DOM元素
const currentBattleInfo = document.getElementById('current-battle-info');
const currentDateTime = document.getElementById('current-date-time');
const nextBattleElem = document.getElementById('next-battle');
const calendarMonthElem = document.getElementById('calendar-month');
const calendarDaysElem = document.getElementById('calendar-days');
const prevMonthBtn = document.getElementById('prev-month');
const nextMonthBtn = document.getElementById('next-month');
const currMonthBtn = document.getElementById('current-month');

// 计算当天战场索引 (考虑23:00之后切换到新战场)
function getCurrentBattleIndex(targetDate = new Date()) {
    // 如果时间在23:00之后，则视为第二天
    let effectiveDate = new Date(targetDate);
    if (effectiveDate.getHours() >= 23) {
        effectiveDate.setDate(effectiveDate.getDate() + 1);
    }
    
    // 计算与初始日期的天数差
    const oneDay = 24 * 60 * 60 * 1000;
    // 修正过了中午12点就会跳到下一天的问题
    const diffDays_real = Math.trunc((effectiveDate - initialDate) / oneDay);
    // 修正负向计算错误问题
    if (diffDays_real < 0){
        const diffDays = Math.round(Math.abs(diffDays_real % 4 + 4));
        return diffDays % 4;
    }
    else {
        const diffDays = Math.round(Math.abs(diffDays_real));
        return diffDays % 4;
    }
}

// 按指定日期获取战场数据
function getBattleData(date) {
    const index = getCurrentBattleIndex(date);
    return battleData[index];
}

// 渲染当前战场
function renderCurrentBattle() {
    const now = new Date();
    const isAfter23 = now.getHours() >= 23;
    const battle = getBattleData(now);
    
    currentBattleInfo.className = 'battle-info ' + battle.bgClass;
    
    currentBattleInfo.innerHTML = `
        <div class="battle-name">${battle.name}</div>
        <div class="battle-type">${battle.type}</div>
        <div class="battle-icon">
            <i class="fas ${battle.type === '阵地战' ? 'fa-chess-rook' : 
                                battle.type === '争夺战' ? 'fa-gem' : 
                                battle.type === '碎冰战' ? 'fa-snowflake' : 
                                'fa-trophy'} fa-3x"></i>
        </div>
    `;
    
    currentDateTime.innerHTML = `
        <p>当前日期: <strong>${formatDate(now)}</strong></p>
        <p>当前时间: <strong>${formatTime(now)} (GMT+8)</strong></p>
        <p>今日战场有效时间: <strong>00:00 - 22:59(GMT+8)</strong></p>
        ${isAfter23 ? `<p style="color:#f7d777;margin-top:10px;">注意：已超过23:00，当前显示为次日战场</p>` : ''}
    `;

    
    // 下一战场
    // 此处先声明变量然后置0
    // 如果不大于23，则加1，否则不变
    const nextBattleIndex = !isAfter23 ? (getCurrentBattleIndex(now) + 1) % 4:(getCurrentBattleIndex(now)) % 4;
    const nextBattle = battleData[nextBattleIndex];
    // 既然上面修正了，此处就没必要再修正了，总之过了0点就对齐了
    nextBattleElem.innerHTML = `
        ${formatDate(new Date(now.setDate(now.getDate() + 1)))}: 
        <span style="color:${getBattleColor(nextBattleIndex)};margin-left:5px;">
            <strong>${nextBattle.name}（${nextBattle.type}）</strong>
        </span>
    `;
}

// 生成月份日历
function renderCalendar() {
    const firstDay = new Date(calendarYear, calendarMonth, 1);
    const lastDay = new Date(calendarYear, calendarMonth + 1, 0);
    const daysInMonth = lastDay.getDate();
    
    // 设置显示的月份
    calendarMonthElem.textContent = `${calendarYear}年${calendarMonth + 1}月`;
    
    // 清空当前日历
    calendarDaysElem.innerHTML = '';
    
    // 计算第一天是星期几 (0 = 星期日, 1 = 星期一, ...)
    const firstDayIndex = firstDay.getDay();
    
    // 添加空白日 (在月初之前)
    for (let i = 0; i < firstDayIndex; i++) {
        const dayElement = document.createElement('div');
        dayElement.className = 'day empty';
        calendarDaysElem.appendChild(dayElement);
    }
    
    // 添加实际日期
    const today = new Date();
    const todayIsAfter23 = today.getHours() >= 23;
    const currentDay = todayIsAfter23 ? today.getDate() + 1 : today.getDate();
    
    for (let day = 1; day <= daysInMonth; day++) {
        const dayElement = document.createElement('div');
        const date = new Date(calendarYear, calendarMonth, day);
        const battle = getBattleData(date);
        
        dayElement.className = 'day';
        dayElement.classList.add(battle.bgClass);
        
        // 如果是今天且时间在23:00之前，或者明天且时间在23:00之后
        const isHighlightDay = 
            (calendarYear === today.getFullYear() && 
                calendarMonth === today.getMonth() && 
                day === currentDay);
        
        if (isHighlightDay) {
            dayElement.classList.add('today');
        }
        
        dayElement.innerHTML = `
            <div class="day-num">${day}</div>
            <div class="day-battle">${battle.short}</div>
        `;
        
        calendarDaysElem.appendChild(dayElement);
    }
}

// 格式化日期
function formatDate(date) {
    return `${date.getFullYear()}年${(date.getMonth() + 1).toString().padStart(2, '0')}月${date.getDate().toString().padStart(2, '0')}日`;
}

// 格式化时间
function formatTime(date) {
    return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
}

// 获取战场颜色
function getBattleColor(index) {
    switch(index) {
        case 0: return '#4a6fa5';
        case 1: return '#d65d0e';
        case 2: return '#17ab8d';
        case 3: return '#b16286';
        default: return '#ffffff';
    }
}

// 事件监听器
prevMonthBtn.addEventListener('click', () => {
    calendarMonth--;
    if (calendarMonth < 0) {
        calendarMonth = 11;
        calendarYear--;
    }
    renderCalendar();
});

nextMonthBtn.addEventListener('click', () => {
    calendarMonth++;
    if (calendarMonth > 11) {
        calendarMonth = 0;
        calendarYear++;
    }
    renderCalendar();
});

currMonthBtn.addEventListener('click', () => {
    const now = new Date();
    calendarMonth = now.getMonth();
    calendarYear = now.getFullYear();
    renderCalendar();
});

// 初始加载页面
//document.getElementById('update-date').textContent = formatDate(new Date());
renderCurrentBattle();
renderCalendar();

// 每秒更新一次时间和战场信息
setInterval(renderCurrentBattle, 1000);